import timing from "./timing";

const calcStatistics = function (dataList) {
    var size = dataList.length;
    var sum = dataList.reduce(function (preVal, curVal) {
        return preVal + curVal;
    }, 0);
    var average = sum / size;
    var variance = dataList.reduce(function (preVal, curVal) {
        return preVal + Math.pow(curVal - average, 2);
    }, 0) / size;
    var standardDeviation = Math.sqrt(variance);

    return {
        size: size,
        sum: sum,
        average: average,
        variance: variance,
        standardDeviation: standardDeviation
    }
}

const dataToExcel = function () {
    var isStartRecorded = window.sessionStorage.getItem("isStartRecorded");
    var records = [];
    if (isStartRecorded) {
        records = JSON.parse(window.sessionStorage.getItem("timingRecords"));
    }

    console.log("=== dataToExcel ===");
    console.log(records);

    var wb = XLSX.utils.book_new();
    //TODO ...


}

const generateXLSX = function (targetName) {
    //TODO 
    var wb = XLSX.utils.book_new();

    wb.Props = {
        Title: "Front End Performance Benchmark",
        Subject: "Benchmark",
        Author: "Issac",
        CreatedDate: new Date()
    };
    wb.SheetNames.push("Benchmark Sheet");
    var ws_data = dataToWs();
    var ws = XLSX.utils.aoa_to_sheet(ws_data);
    wb.Sheets["Benchmark Sheet"] = ws;
    var wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
    var fileName = this.generateFileName(targetName);
    var file = XLSX.writeFile(wb, fileName);
    var link = document.createElement('a');
    link.download = fileName;
    link.click();
}

const generateFileName = function (targetName) {
    return targetName + "_benchmark_" + Date.now() + ".xlsx"
}

const dataToWs = function () {
    //TODO 
    var startBenchmark = sessionStorage.getItem("startBenchmark");
    if (startBenchmark) {
        var records = JSON.parse(sessionStorage.getItem("records"));
        var ws = [["totalTime", "domTime"]].concat(records.map(function (record) {
            return [record.totalTime, record.domTime];
        }));

        ws.push([]);
        ws.push(["recordSize", "totalAvg", "domAvg", "totalStandardDeviation", "domStandardDeviation"]);

        ws.push([sessionStorage.getItem("recordSize"),
        sessionStorage.getItem("totalAvg"),
        sessionStorage.getItem("domAvg"),
        sessionStorage.getItem("totalStandardDeviation"),
        sessionStorage.getItem("domStandardDeviation")]);

        return ws;
    } else {
        return [["The benchmark is not started yet"]];
    }
}

const stopRecord =  function () {
    sessionStorage.removeItem("shouldRecord");
}

const startRecord=  function () {
    sessionStorage.setItem("shouldRecord", true);
    window.location.reload();
}


const benchamark = {
    startRecord: function () {
        var limitTimes = window.sessionStorage.getItem("limit") || "10";
        limitTimes = parseInt(limitTimes);

        var data = timing.getSimpleResult();

        var isStartRecorded = window.sessionStorage.getItem("isStartRecorded");
        var records;
        if (isStartRecorded) {
            records = JSON.parse(window.sessionStorage.getItem("timingRecords"));
            records.push(data);
        } else {
            window.sessionStorage.setItem("isStartRecorded", 1);
            records = [data];
        }

        var totalStatistics = calcStatistics(records.map(function (data) {
            return data.totalTime;
        }));
        var domStatistics = calcStatistics(records.map(function (data) {
            return data.domTime;
        }));

        window.sessionStorage.setItem("timingRecords", JSON.stringify(records));

        window.sessionStorage.setItem("recordSize", records.length);

        window.sessionStorage.setItem("totalSum", totalStatistics.sum);
        window.sessionStorage.setItem("totalAvg", totalStatistics.average);
        window.sessionStorage.setItem("totalVariance", totalStatistics.variance);
        window.sessionStorage.setItem("totalStandardDeviation", totalStatistics.standardDeviation);

        window.sessionStorage.setItem("domSum", domStatistics.sum);
        window.sessionStorage.setItem("domAvg", domStatistics.average);
        window.sessionStorage.setItem("domVariance", domStatistics.variance);
        window.sessionStorage.setItem("domStandardDeviation", domStatistics.standardDeviation);

        if (records.length < limitTimes) {
            location.reload();
        }
    },
    exportToExcel: function () {
        var script = document.createElement("script");
        script.src = "https://unpkg.com/xlsx/dist/xlsx.full.min.js";
        script.addEventListener("load", function () {
            setTimeout(() => {
                dataToExcel();
            }, 1000);

            window.benchamark.exportToExcel = function () {
                dataToExcel();
            }
        });
        document.body.appendChild(script);
    }
}


export default benchamark;
